import fetch from 'fermionjs/lib/fetch';
import pkg from '../../../package.json';
import errorCodesBuilder from '../helpers/errorCodesBuilder';
const { name } = pkg;

const errorCodes = errorCodesBuilder();

export default function sendWechatMessage({ url, wxOpenId, templateId, data }) {
	const {
		log,
		app: {
			config: {
				[name]: {
					wechatSendMessageApi,
					wechatUser,
					wechatPassword,
					wechatAlertTemplateId,
					// wechatReverseTemplateId,
				},
			},
		},
	} = this;

	log.info({ wxOpenId, data }, '发送微信消息');

	const payload = {
		url,
		data,
		template_id: templateId || wechatAlertTemplateId,
		user_id: wxOpenId,
	};
	return fetch(wechatSendMessageApi, {
		method: 'POST',
		headers: {
			Authorization: `Basic ${Buffer.from(
				`${wechatUser}:${wechatPassword}`
			).toString('base64')}`,
		},
		body: JSON.stringify(payload),
	})
		.then(response => {
			if (response.errmsg && response.errmsg !== 'ok') {
				throw new Error(JSON.stringify(response));
			}
			return response;
		})
		.catch(err => {
			const error = errorCodes['[0E]发送微信消息失败'].from(err);
			log.error({ error, payload }, error.rawMessage);
			throw error;
		});
}
